import cv2
import mediapipe as mp
import time


class FaceMesh():
    def __init__(self,static_image_mode=False,
               max_num_faces=1,
               refine_landmarks=False,
               min_detection_confidence=0.5,
               min_tracking_confidence=0.5):
        self.static_image_mode = static_image_mode
        self.max_num_faces = max_num_faces
        self.refine_landmarks = refine_landmarks
        self.min_detection_confidence = min_detection_confidence
        self.min_tracking_confidence = min_tracking_confidence

        self.mpFaceMesh = mp.solutions.face_mesh
        self.faceMesh = self.mpFaceMesh.FaceMesh()
        self.mpDraw = mp.solutions.drawing_utils
        self.facespce = self.mpDraw.DrawingSpec(thickness=1,circle_radius=2)

    def findFaceMesh(self,frame,draw=True):
        frameRGB = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
        self.result = self.faceMesh.process(frameRGB)
        facelist =[]
        if self.result.multi_face_landmarks:
            for face_landmarks in self.result.multi_face_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(frame,face_landmarks,self.mpFaceMesh.FACEMESH_CONTOURS,self.facespce,self.facespce)
                face = []
                for id, lm in enumerate(face_landmarks.landmark):
                    h, w, c = frame.shape
                    x, y = int(lm.x * w), int(lm.y * h)
                    cv2.putText(frame, str(int(id)), (x, y), cv2.FONT_HERSHEY_PLAIN, 0.3, (0, 255, 0), 1)
                    face.append([x,y])
                facelist.append(face)
        return frame, facelist


def main():
    cap = cv2.VideoCapture(0)
    Ptime = 0
    detector = FaceMesh()
    while True:
        ret,frame = cap.read()
        frame,facelist = detector.findFaceMesh(frame)
        if len(facelist)!=0:
            print(facelist)
        Ctime = time.time()
        fps = 1/(Ctime-Ptime)
        Ptime = Ctime
        cv2.putText(frame,'FPS:'+str(int(fps)),(10,70),cv2.FONT_HERSHEY_PLAIN,3,(0,255,0),3)
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) == ord('q'):
            break

if __name__ == '__main__':
    main()
